﻿/////////////////////////////////////////////////////////////////
//File: BlogInfo.cs
//Description: 
//Copyright© 2011 Moliu
//History:
//  2011-3-14 0:38:21    CodeSmith5.0.1    Original Version
/////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using MAF.Common;
using System.Threading;
using System.Security;
using System.Security.Principal;
using My.Blog.Domain.Entities;
using My.Blog.Domain.Interfaces;
using My.Blog.Business.Persistence;



namespace My.Blog.Business.Security
{
    /// <summary>
    /// 
    /// </summary>
    public class SecurityUtility
    {
        /// <summary>
        /// 是否登录
        /// </summary>
        public static bool IsLogon
        {
            get
            {
                if (null == Thread.CurrentPrincipal) { return false; }
                return (typeof(BlogPrincipal) == Thread.CurrentPrincipal.GetType())
                    && (true == Thread.CurrentPrincipal.Identity.IsAuthenticated);
            }
        }

        /// <summary>
        /// 用户的Id,其实就是BlogId
        /// </summary>
        public static string UserId
        {
            get 
            {
                if (!IsLogon) { return "0"; }
                return Thread.CurrentPrincipal.Identity.Name;
            }
        }

        /// <summary>
        /// LogonUser
        /// </summary>
        public static void LogonUser(string id, string password)
        {
            BlogIdentity identity = new BlogIdentity(id, password);
            BlogPrincipal principal = new BlogPrincipal(identity);

            if (true != principal.Identity.IsAuthenticated)
            { throw new SecurityException("身份验证失败，用户名或密码错误！"); }

            Thread.CurrentPrincipal = principal;
        }

        /// <summary>
        /// 是否管理员角色，本系统只有管理员拥有角色
        /// </summary>
        /// <param name="roles">角色字符串</param>
        /// <returns></returns>
        public static bool IsInRole(string roles)
        {
            if (!IsLogon) { return false; }
            return Thread.CurrentPrincipal.IsInRole(roles);
        }

        /// <summary>
        /// 是否博主
        /// </summary>
        /// <param name="blogId">博客的Id,其实也就是UserId</param>
        /// <returns></returns>
        public static bool IsBlogMaster(string blogId)
        {
            if (!IsLogon) { return false; }
            if (string.IsNullOrEmpty(blogId)) { return false; }
            return blogId == UserId;
        }

        /// <summary>
        /// 是否管理员，IsInRole方法的快捷方式
        /// </summary>
        public static bool IsBlogAdmin
        {
            get
            {
                if (!IsLogon) { return false; }
                return IsInRole("Admin");
            }
        }
    }
}